package com.example.wxchatdemo;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Looper;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.wxchatdemo.Files.FileListPojo;
import com.example.wxchatdemo.Files.FilesShowAdapter;
import com.example.wxchatdemo.Files.ImgsAdapter;
import com.example.wxchatdemo.Files.MainFiles;
import com.example.wxchatdemo.Files.putfiles;
import com.example.wxchatdemo.SQLitess.SQLites;
import com.example.wxchatdemo.Sockets.IOUtil;

import com.example.wxchatdemo.Sockets.TestClient;
import com.example.wxchatdemo.Sockets.TestClient2;
import com.example.wxchatdemo.pojo.WeChat_msgs;
import com.example.wxchatdemo.utils.MyThread;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class speackActivity2 extends AppCompatActivity {
    private String address="100.2.193.182";
    private List<speacking> mData = null;
    private Context mContext;
    //图片适配器
    private LinkedList<String> mData_imgs;

    private speackingAdapter mAdapter = null;
    private ListView list_animal;
    //上部分
    private Button return_main,show_all;
    private TextView F_name;
    //下部分-输入栏
    private Button emo,send,img_cream;
    private EditText editText;
    private String my_id,other_id;
    //数据库
    private SQLiteDatabase db;
    private SQLites sqLites;

    private StringBuilder sb;
    private int i = 1;
    //Socket
    private int isclose=0;
    //用户名
     private String f_name;
     private int g=0;

    public Socket getSocket_files() {
        return socket;
    }

    public void setSocket_files(Socket socket) {
        this.socket = socket;
    }

    //聊天socket
    Socket socket_files=null;
     //文件list布局
    RelativeLayout relativeLayout=null;
    RelativeLayout Layout_getfiles=null;
    private Button btn_get_file;
    ListView list_files=null;
    LinkedList<FileListPojo> list__files=null;
    //文件操作按钮
    private Button gotofile,up;

    public String getGet_file_name() {
        return get_file_name;
    }

    public void setGet_file_name(String get_file_name) {
        this.get_file_name = get_file_name;
    }

    private String  get_file_name;
    //文件列表适配器
    FilesShowAdapter filesShowAdapter=null;
    int file_vis=1;
    //图片list

    //
    //文件路径
    private String File_Path;
    public String getFile_Path() {
        return File_Path;
    }
    public void setFile_Path(String file_Path) {
        File_Path = file_Path;
    }
     //SOCKET
    private Socket socket;
    private PrintWriter printWriter;
    private  int isno;
    BufferedReader bufferedReader = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //图片list
        mData_imgs=new LinkedList<String>();
        //设置默认路径
        setFile_Path("/storage/emulated/0/AppFiles/");
        setGet_file_name("ac.jpg");
//解决发送消息的问题----ndroid.os.NetworkOnMainThreadException
/*在Android4.0以后，会发现，只要是写在主线程（就是Activity）中的HTTP请求，运行时都会报错，*/
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }


        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_item);
        mContext = speackActivity2.this;
        list_animal = (ListView) findViewById(R.id.list_animal);
        list_files = (ListView) findViewById(R.id.list_files);
        //查找上部分内容
        return_main=(Button) findViewById(R.id.return_main);
        show_all=(Button) findViewById(R.id.show_all);
        F_name=(TextView)findViewById(R.id.F_name);
        //查找下部分内容up
        emo=(Button) findViewById(R.id.emo);
        img_cream=(Button) findViewById(R.id.img_cream);
        gotofile=(Button) findViewById(R.id.gotofile);
        up=(Button) findViewById(R.id.up);
        send=(Button) findViewById(R.id.send);
        editText=(EditText) findViewById(R.id.editext);
        F_name=(TextView)findViewById(R.id.F_name);
        //
        relativeLayout=(RelativeLayout)findViewById(R.id.Layout_R);
        Layout_getfiles=(RelativeLayout)findViewById(R.id.Layout_getfiles);
        btn_get_file=(Button) findViewById(R.id.btn_get_file);
        //文件接收不可见
        Layout_getfiles.setVisibility(View.GONE);


        //创建数据库
        sqLites = new SQLites(mContext, "my.db", null, 1);
        Intent intents = getIntent();
        Bundle bundle=intents.getExtras();
//设置发送文件下拉表不可见
        relativeLayout.setVisibility(View.GONE);

        //对方账号识别；---上一个ativity发送过来的；
        String id = bundle.getString("f_id");
        f_name=bundle.getString("f_name");
        F_name.setText(f_name);

        my_id=bundle.getString("my_id");
        //设置对手id
        other_id=id;

//数据库查询结果--mysql
      MyThread myThread=new MyThread(my_id,other_id,null,"");
      myThread.start();

        List<WeChat_msgs>  weChat_msgs= null;
        try {
            weChat_msgs = myThread.call();
        } catch (Exception e) {
            e.printStackTrace();
        }


        mData = new LinkedList<speacking>();


        int x=0;
//查看网络是否异常，网络异常则调用本地数据库；如何继续渲染
try{
    weChat_msgs.size();
}
catch (Exception e){
    System.out.println("speackAcivity227==网络异常！！！，连接服务器失败");
    Toast.makeText(speackActivity2.this, "网络异常，请查看网络是否畅通", Toast.LENGTH_LONG).show();
//执行查询本地数据库
    x=2;
}

if (x!=0){

    long startTime = System.currentTimeMillis();
//查询本地聊天记录
    weChat_msgs=GetNoW(my_id,other_id);
}

        long startTime = System.currentTimeMillis();


        //根据查出来的数据设置聊天消息位置
        for (int i=0;i<weChat_msgs.size();i++){
            //System.out.println("查到的聊天记录"+weChat_msgs.toString());
            if ("sent".equals(weChat_msgs.get(i).getStatus())){
                // System.out.println("安排在左边");
                // System.out.println("=======>左边"+f_name);
                mData.add(new speacking(weChat_msgs.get(i).getContent()+"", weChat_msgs.get(i).getTimes()+"", weChat_msgs.get(i).getMyid(),weChat_msgs.get(i).getTimes()+""));
                continue;
            }
            //System.out.println("安排在右边");
            // System.out.println(weChat_msgs.get(i).getStatus()+"当前状态是这个-----");
            mData.add(new speacking(weChat_msgs.get(i).getContent()+"", weChat_msgs.get(i).getTimes()+"", weChat_msgs.get(i).getYouid(),weChat_msgs.get(i).getTimes()+""));
        }

//        mData.add(new speacking("我爱你啊啊啊啊ewdweeeeee韦恩韦德 物非人非二分阿人个  七二杠阿二给微软个人情感给企鹅二啊", "18:60",other_id));

       mData.add(new speacking("不是吧，这都不给高分？？？", "3274372842",other_id));

        mAdapter = new speackingAdapter((LinkedList<speacking>) mData, mContext,my_id,other_id);
        list_animal.setAdapter(mAdapter);
//定位在最后一条
        list_animal.setSelection(ListView.FOCUS_DOWN);
//socket启动
        new Thread(new Runnable() {
            @Override
            public void run() {
                TestClient2 testClient=new TestClient2();
                try {
                    testClient.init();
                } catch (IOException e) {
                  //  e.printStackTrace();
                    System.out.println("229--speack2服务器启动异常");
                }
            }
        }).start();

//为发送文件list添加点击时间
        list_files.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {
                //文件名
                String Filename= list__files.get(index).getFileName();
                System.out.println("获取当前点击的文件"+Filename);
                //点击了文件
                if (Filename.contains(".")){
                    speackActivity2.this.runOnUiThread(new Runnable() {
                        public void run() {
                            // imageView.setImageURI(Uri.fromFile(new File("/storage/emulated/0/AppFiles/"+Filename)));

                            mData_imgs.add(new String(getFile_Path()+Filename));


                            //打开文件
                            Thread thread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        sent_file(Filename + "-sent");
                                        Looper.prepare();
                                        Toast.makeText(speackActivity2.this, "发送文件"+Filename+"成功", Toast.LENGTH_SHORT).show();
                                        Looper.loop();
                                    } catch (IOException e) {
                                        //
                                        System.out.println("点击listview，发送文件失败了--167--Main");
                                    }
                                }
                            });
                            thread.start();
                        }

                    });

                }else{
//点击了文件夹
                    String[] strings=getFile_Path().split("/");
                    for (int i=0;i<strings.length;i++){
                    }
                    String f="";
                    for (int i=0;i<strings.length;i++){
                        f=f+strings[i]+"/";
                    }
                    System.out.println("点击listview-最后拼接好的----"+f+Filename+"/");
                    setFile_Path(f+Filename+"/");
                    speackActivity2.this.runOnUiThread(new Runnable() {
                        public void run() {
                            showFilePath(getFile_Path());
                        }});

                }


            }
        });
//返回上一级目录
        up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                speackActivity2.this.runOnUiThread(new Runnable() {
                                                 public void run() {

                                                     String[] splitss = getFile_Path().split("/");
                                                     if (splitss.length==2){
                                                         System.out.println("文件以到终点");
                                                         return;
                                                     }

                                                     splitss[splitss.length - 1] = "";
                                                     String PATH = "";
                                                     for (int i = 0; i < splitss.length; i++) {
                                                         if (splitss[i] != "") {
                                                             PATH = PATH + splitss[i] + "/";
                                                         }
                                                     }
                                                     System.out.println("PATH====" + PATH );
                                                     setFile_Path(PATH);
                                                     showFilePath(getFile_Path());

                                                 }

                                             }
                );

            }
        });
//打开相册
        img_cream.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                speackActivity2.this.runOnUiThread(new Runnable() {
                    public void run() {

                        setFile_Path("/storage/emulated/0/DCIM/Camera/");
                        showFilePath(getFile_Path());


                    }
                });

            }
        });
//回到默认文件夹
        gotofile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                speackActivity2.this.runOnUiThread(new Runnable() {
                    public void run() {
                        setFile_Path("/storage/emulated/0/AppFiles/");
                        System.out.println("打开默认文件夹");
                        showFilePath(getFile_Path());
                    }
                });

            }
        });
//返回按钮
        return_main.setOnClickListener(new View.OnClickListener() {
           //

            @Override
            public void onClick(View view) {
                //跳转页面
               Intent open_main=new Intent(speackActivity2.this,Main_one.class);
               startActivity(open_main);
               /* try {
                    socket.close();
                } catch (IOException e) {
                    //
                    System.out.println("292-socket关闭异常");
                }*/
            }
        });

//查看详情按钮
        show_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // 开一个线程完成网络请求操作
                new Thread(new Runnable()
                {

                    List listss = new ArrayList<WeChat_msgs>();

                    @Override
                    public void run() {
                        List listsss = new ArrayList<WeChat_msgs>();

                        String result = null;
                        OkHttpClient client = new OkHttpClient();

                        Request request = new Request.Builder()
                                .url("http://"+address+":8085/GetMsgs?youid="+"3"+"&myid="+my_id).build();
                        //数据是：//phone="+phone.getText()+"&name="+username.getText()+"&password="+password.getText())

                        try (Response response = client.newCall(request).execute()) {

                            result = response.body().string();
                            //转化JSON函数
                            List<Map<String, String>> list = TransJSON(result);

                            System.out.println("获得结果集数量"+list.size());
                            //循环取出json
                            //  while (inde<list.size()){
                            for (int i=0;i<list.size();i++){
                                String id=list.get(i).get("id");
                                String myid= list.get(i).get("myid");
                                String youid= list.get(i).get("youid");
                                String content= list.get(i).get("content");
                                String times= list.get(i).get("times");
                                //System.out.println("GetJSon方法结果集"+"id="+id+"---myid--="+myid+"--youid="+youid+"--time="+times+"==="+content);


                                //创建实体类
                                WeChat_msgs weChat_msgs = new WeChat_msgs();
                                weChat_msgs.setId(id);
                                weChat_msgs.setMyid(myid);
                                weChat_msgs.setContent(content);
                                weChat_msgs.setTimes(times);
                                weChat_msgs.setYouid(youid);
                                listsss.add(weChat_msgs);

                                System.out.println("不是最后获取一下长度-----"+listss.size());
                            }




                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        listss=listsss;   }//run




                }).start();



            }


        });

//表情按钮
        emo.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View view) {
//启动线程打开发送文件的图像
              speackActivity2.this.runOnUiThread(new Runnable() {
         public void run() {
        showFilePath("/storage/emulated/0/AppFiles/");
        if (file_vis%2==1){
            relativeLayout.setVisibility(View.VISIBLE);

        }else {
            relativeLayout.setVisibility(View.GONE);
        }
        file_vis++;

                     /*   Intent intent = new Intent(speackActivity2.this, MainFiles.class);
                        startActivity(intent);
*/

                    }
              });


                /*
                List list=new ArrayList<WeChat_msgs>();

                SQLiteDatabase dbs = sqLites.getReadableDatabase();
                Cursor cursor =  dbs.rawQuery("SELECT * FROM wechat ",null      );
                //查询数据库
                System.out.println(cursor.getCount()+"数据库条数");
                while (cursor.moveToNext())
                {

                    Long personid = cursor.getLong(cursor.getColumnIndex("id"));
                    int  youid = cursor.getInt(cursor.getColumnIndex("youid"));
                    int  myid = cursor.getInt(cursor.getColumnIndex("myid"));
                    String contents=cursor.getString(cursor.getColumnIndex("content"));
                    long timess = cursor.getLong(cursor.getColumnIndex("times"));
                    String status=cursor.getString(cursor.getColumnIndex("status"));
        list.add(new WeChat_msgs(personid+"",youid+"",myid+"",contents,timess+"",status));
               System.out.println(personid+"----"+"||"+youid+"||"+"---"+"||"+myid+"||"+"-------------"+"||"+contents+"||"+"----"+timess+"---"+status);
                }
                cursor.close();//查找数据库

           */ }
        });
//接收文件按钮
        btn_get_file.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                speackActivity2.this.runOnUiThread(new Runnable() {
                    public void run() {
                        System.out.println("线程启动了");
                        putfiles putfiles=new putfiles(getGet_file_name());
                        Layout_getfiles.setVisibility(View.GONE);
                        Toast.makeText(speackActivity2.this, "接收文件"+get_file_name+"成功", Toast.LENGTH_SHORT).show();
                        try {
                            putfiles.putfiles_one();
                        } catch (IOException e) {

                        }
                    }
                });



            }
        });


    }
    public String getContent(EditText editText){
        return editText.getText().toString();

    }

//发送按钮
     int Sent_msgs(String id,String youid,String my_id,String content,String times,String status){
        int msg=0;
//        发送网络请求，并获取数据
                // 开一个线程完成网络请求操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String result = null;
                        OkHttpClient client = new OkHttpClient();

                        Request request = new Request.Builder()
                                .url("http://"+address+":8085/Login?id="+id+"&youid="+youid+"&myid="+my_id+" &content="+content+" &times="+times+"&status="+status ).build();
                                        //数据是：//phone="+phone.getText()+"&name="+username.getText()+"&password="+password.getText())

                        try (Response response = client.newCall(request).execute()) {

                            result = response.body().string();

                            System.out.println("服务器返回消息==》"+result);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }

                }).start();
        return msg;
    }


//转换json字符串方法
    List<Map<String,String>> TransJSON(String argss){
        //创建返回数据
        List<Map<String,String>> list = new ArrayList<>();
        Map map=new HashMap<String,String >();


        String jsonArray=argss;
        StringBuffer sb=new StringBuffer();
        //需要使用的JSON的parseArray方法，将jsonArray解析为object类型的数组
        JSONArray objects = JSON.parseArray(jsonArray);
        int i=0;
       // for(int i=0;i<objects.size();i++){
        while (i<objects.size()){
            Map map2=new HashMap<String,String >();
            //通过数组下标取到object，使用强转转为JSONObject，之后进行操作
            JSONObject object = (JSONObject) objects.get(i);
            String id = object.getString("id");
            String youid = object.getString("youid");
            String myid= object.getString("myid");
            String content= object.getString("content");
            String times= object.getString("times");
            String status= object.getString("status");
            //System.out.println("TranJson方法结果集"+"id="+id+"---myid--="+myid+"--youid="+youid+"--time="+times+"==="+content);

            //把数据放入map中
            map2.put("id",id);
            map2.put("myid",myid);
            map2.put("youid",youid);
            map2.put("content",content);
            map2.put("times",times);
            map2.put("status",status);
            list.add(map2);
            i++;
        }
        return list;
    }
//***未使用=从网络查询两条记录
    List<WeChat_msgs> GetMsgs(String youid, String my_id){
        int msg=0;
      List lists = new ArrayList<WeChat_msgs>();

//        发送网络请求，并获取数据
        // 开一个线程完成网络请求操作
       new Thread(new Runnable()
       {

           List listss = new ArrayList<WeChat_msgs>();



            @Override
            public void run() {
                List listsss = new ArrayList<WeChat_msgs>();

                String result = null;
                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder()
                        .url("http://"+address+":8085/GetMsgs?youid="+youid+"&myid="+my_id).build();
                //数据是：//phone="+phone.getText()+"&name="+username.getText()+"&password="+password.getText())

                try (Response response = client.newCall(request).execute()) {

                    result = response.body().string();
                    //转化JSON函数
                    List<Map<String, String>> list = TransJSON(result);

                    System.out.println("获得结果集数量"+list.size());
                    //循环取出json
                  //  while (inde<list.size()){
                    for (int i=0;i<list.size();i++){
                        String id=list.get(i).get("id");
                        String myid= list.get(i).get("myid");
                        String youid= list.get(i).get("youid");
                        String content= list.get(i).get("content");
                        String times= list.get(i).get("times");
                       //System.out.println("GetJSon方法结果集"+"id="+id+"---myid--="+myid+"--youid="+youid+"--time="+times+"==="+content);


                        //创建实体类
                        WeChat_msgs weChat_msgs = new WeChat_msgs();
                        weChat_msgs.setId(id);
                        weChat_msgs.setMyid(myid);
                        weChat_msgs.setContent(content);
                        weChat_msgs.setTimes(times);
                        weChat_msgs.setYouid(youid);
                        listsss.add(weChat_msgs);

                        System.out.println("不是最后获取一下长度-----"+listss.size());
                    }




                } catch (IOException e) {
                    e.printStackTrace();
                }

                listss=listsss;   }//run




         }).start();
        return lists;
    }

//无网络情况下，从本地数据库查找信息
    List<WeChat_msgs> GetNoW( String myids,String youids){
        List list=new ArrayList<WeChat_msgs>();

        SQLiteDatabase dbs = sqLites.getReadableDatabase();
        Cursor cursor =  dbs.rawQuery("SELECT * FROM wechat where myid="+myids+" and youid="+youids,null      );
        //查询数据库
        System.out.println(cursor.getCount()+"数据库条数");
        while (cursor.moveToNext())
        {
            Long personid = cursor.getLong(cursor.getColumnIndex("id"));
            int  youid = cursor.getInt(cursor.getColumnIndex("youid"));
            int  myid = cursor.getInt(cursor.getColumnIndex("myid"));
            String contents=cursor.getString(cursor.getColumnIndex("content"));
            long times = cursor.getLong(cursor.getColumnIndex("times"));
            String status=cursor.getString(cursor.getColumnIndex("status"));
            list.add(new WeChat_msgs(personid+"",myid+"",youid+"",times+"",contents+"",status));
            System.out.println(personid+"----"+"||"+youid+"||"+"---"+"||"+myid+"||"+"-------------"+"||"+contents+"||"+"----"+times+"---"+status);
        }
        cursor.close();//查找数据库

        return list;
    }


//socket的连接请求
   class TestClient2 {

        private Socket socket;
        private InputStream is;
        private OutputStream os;
        private String response = "";
        private Scanner scanner;
        private  String msgs;


        public String getMsgs() {
            return msgs;
        }

        public void setMsgs(String msgs) {
            this.msgs = msgs;
        }

        public void init() throws IOException {
//发送消息到服务器
            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //获取7位的随机数
                    Calendar cal= Calendar.getInstance();
                    int m=cal.get(Calendar.MONTH);
                    int d=cal.get(Calendar.DATE);
                    int h=cal.get(Calendar.HOUR_OF_DAY);
                    int mi=cal.get(Calendar.MINUTE);
                    int s=cal.get(Calendar.SECOND);
                    Random rand = new Random();
                    int i = rand.nextInt(100);

                    // System.out.println("现在随机数"+times);
                    long time_no=new Date().getTime();

                    //新增聊天记录---发送信息---判断是否输入是空
                    if (!"".equals(getContent(editText)))
                    {
///********手机端失败
                        //获取时间---秒计算
                        long timeMillis = System.currentTimeMillis();
                        //生成简单时间
                        SimpleDateFormat sdfTwo =new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒E", Locale.getDefault());
                        //星期几？
                        String time44 = sdfTwo.format(timeMillis);
                        mData.add(new speacking(getContent(editText), timeMillis+"",my_id+""));
                        mAdapter = new speackingAdapter((LinkedList<speacking>) mData, mContext,my_id,other_id);

                        try {
                            if (os!=null) {
                                //  Toast.makeText(speackActivity2.this, "准备发送消息给服务器", Toast.LENGTH_LONG).show();
//*****第一次就发送本人消息给服务器
                                IOUtil.writeString(os, "sto" + " " + other_id + " " + getContent(editText));
                                //储存数据到mysql数据库
                                //  db = sqLites.getWritableDatabase();
                                //参数依次是：表名，强行插入null值得数据列的列名，一行记录的数据
                                //  db.execSQL("INSERT INTO `wechat`(`id`, `youid`, `myid`, `content`, `times`,'status') VALUES (?, ?, ?, ?, ?,?);", new String[]{time_no + "", other_id + "", my_id + "", getContent(editText), time_no+"","sent"});
                                // db.execSQL("INSERT INTO `wechat`(`id`, `youid`, `myid`, `content`, `times`,'status') VALUES (?, ?, ?, ?, ?,?);", new String[]{time_no+1 + "", my_id + "", other_id + "", getContent(editText), time_no+"","re"});
                                //  Sent_msgs(time_no+"",other_id+"",my_id+"",getContent(editText),time_no+"","sent");
                                // Sent_msgs(time_no+1+"",my_id+"",other_id+"",getContent(editText),time_no+"","re");
                                Toast.makeText(speackActivity2.this, "发送成功", Toast.LENGTH_LONG).show();

                            }
                            //储存数据到mysql数据库
                        } catch (IOException e) {
                            // e.printStackTrace();
                            System.out.println("发送客户端消息失败了---661");
                        }
                        //修改当前的ui

                        speackActivity2.this.runOnUiThread(new Runnable() {
                            public void run() {
                                list_animal.setAdapter(mAdapter);
                                //刷新数据，并定位在最后一条信息
                                list_animal.setSelection(ListView.FOCUS_DOWN);
                                //清空输入框内容
                                editText.setText("");

                            }
                        });

                    }
                    else {
                        Toast.makeText(speackActivity2.this, "未填写消息，不能发送", Toast.LENGTH_LONG).show();
                    }
                    //****************发送消息到其他客户端
                }
            });

            try {
                socket = new Socket(address,8888);
                is = socket.getInputStream();
                os = socket.getOutputStream();
//设置socket，共下面的发送文件-进行记录
                setSocket_files(socket);
            } catch (IOException e) {
                System.out.println("socket在speacket2的线程里失败====533");
            }
            response = IOUtil.readString(is);
            //发送自己的id给服务器
            if (g==0){
                IOUtil.writeString(os,my_id);//myid==1
                System.out.println("539==发送本人消息到服务器成功-发送的消息是"+"my_id="+my_id);
                g++;
            }

//发送消息到服务器
            recive();
        }

//接收消息
        public void recive() throws IOException {
            while (true){
                String s = IOUtil.readString(is);
                response = s;
                System.out.println("接收的数据原始====response"+response);
                String[] msgss=response.split(":");
                String ms=msgss[msgss.length-1];
                //收文件数组
                String[] files_an=response.split(" ");
//判断是否是文件

                if (files_an[0].equals("files")){
                    if (files_an[1].equals(my_id)) {


                        System.out.println("需要接收文件" + files_an[files_an.length - 1]);
                        setGet_file_name(files_an[files_an.length - 1]);
                        //弹出
                        speackActivity2.this.runOnUiThread(new Runnable() {
                            public void run() {
                                Layout_getfiles.setVisibility(View.VISIBLE);
                            }
                        });
                    }


                    //需要去接收文件
                }else {


                    System.out.println("接收数据是：" + ms);

                    if (ms.contains(" ")) {
                        continue;
                    }

                    //
                    mData.add(new speacking(ms, "32743372842", other_id));

                    mAdapter = new speackingAdapter((LinkedList<speacking>) mData, mContext, my_id, other_id);
                    //修改当前的ui
                    speackActivity2.this.runOnUiThread(new Runnable() {
                        public void run() {
                            //接收消息
                            list_animal.setAdapter(mAdapter);
                            //定位在最后一条
                            list_animal.setSelection(ListView.FOCUS_DOWN);
                        }
                    });
                    if (socket.isClosed()) {
                        System.out.println("连接或服务器已关闭");
                        break;
                    }
                }

                //
            }
        }

    }
//工具路径展示文件
    public void  showFilePath(String Path){
        //listview生成
      list__files = new LinkedList<FileListPojo>();
        //获取文件路径里的文件列表
        File directory = new File(Path);
//文件夹不存在就创建文件夹
        if (!directory.exists()){
            directory.mkdirs();
        }
        System.out.println(directory);
        //把每个文件添加到flist上
        File[] fList = directory.listFiles();
        if (fList!=null){
            for (int i=0;i<fList.length;i++){
                //  System.out.println("文件:"+fList[i].getName());
                //   System.out.println(fList[i].getAbsolutePath()+"------绝对路径");
                list__files.add(new FileListPojo(fList[i].getName(),fList[i].getAbsolutePath()));
            }
        }else {
            list__files.add(new FileListPojo("无法打开文件！","已到达根目录！"));
        }
        filesShowAdapter = new FilesShowAdapter((LinkedList<FileListPojo>) list__files, mContext);
        list_files.setAdapter(filesShowAdapter);
//        if (file_vis%2==1){
//            relativeLayout.setVisibility(View.VISIBLE);
//
//        }else {
//            relativeLayout.setVisibility(View.GONE);
//        }
//        file_vis++;
        System.out.println("设置文件路径成功");
    }

//根据文件路径发送文件到服务器
    public void sent_file(String filename) throws IOException {
        InputStream is=null;
        OutputStream os=null;
        Socket socket=null;
        FileInputStream fileInputStream=null;

        try{
            socket=new Socket(address,8089);
            if (socket!=null){
                is = socket.getInputStream();
                os= socket.getOutputStream();
            }
        }catch (Exception E){
            System.out.println("连接异常-199-MAin");
        }
        //发送文件名
        byte[] bytes1 = filename.getBytes();
        os.write(bytes1);
        String[] split=filename.split("-");
        //发送文件
        File file=new File(getFile_Path()+"/"+split[0]);
        System.out.println("--");
        fileInputStream=new FileInputStream(file);
        System.out.println(file.length()+"是文件大小+需要发送"+(int)file.length()/4096);
        byte[] bytes=new byte[4096];
        int sive=0;
        int xxx=1;
        while ((sive=fileInputStream.read(bytes))!=-1){
            //发送byte数组到服务器
            os.write(bytes,0,sive);
            xxx++;
        }
        if (os != null) {
            os.flush();
            //os.close();/*这里不能这么使用，不然后面的socket就已经关闭了，导致服务器端的socket接收不完整，会卡在read（byte）里*/
            socket.shutdownOutput();
        }
        if (fileInputStream!=null){
            fileInputStream.close();

        }
        if (!socket.isClosed()){
            System.out.println("文件发送了--关闭阶段"+xxx+"次");
            System.out.println("socket发送文件已关闭");
            // socket.close();/*这里不能这么使用，不然后面的socket就已经关闭了，导致服务器端的socket接收不完整，会卡在read（byte）里*/
        }


//发送消息给Server通知他发文件给对面客户端
        Socket socket_sto=getSocket_files();
        if (socket_sto!=null){
            OutputStream outputStream = socket_sto.getOutputStream();
            IOUtil.writeString(outputStream,"files "+other_id+" "+filename.split("-")[0]);

        }

    }






}
